package com.bjx.common.redisson.config;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@Slf4j
@Configuration
public class RedissonConfig {
    /**
     * redisson协议前缀
     */
    private static final String SCHEMA_PREFIX = "redis://";

    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties){
        log.info("初始化Redisson");
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().
                setAddress(SCHEMA_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort());
        if (StringUtils.hasText(redisProperties.getPassword())) {
            singleServerConfig.setPassword(redisProperties.getPassword());
        }
        singleServerConfig.setTimeout((int) redisProperties.getTimeout().toMillis());
        singleServerConfig.setPingConnectionInterval(30000);
        singleServerConfig.setDatabase(redisProperties.getDatabase());
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }

}
